#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

const int N = 5;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int cnt = 0;

void* Func(void* args)
{
    pthread_detach(pthread_self());//自我分离线程
    //这里要用无符号长整型，因为在Linux下，指针的大小是8字节，而int是4字节，如果使用int会丢失数据
    uint64_t number = (uint64_t)args;
    cout<<"thread-"<<number<<" 创建成功"<<endl;
    while(true)
    {
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&cond,&mutex);
        cnt++;
        cout<<"thread-"<<number<<" cnt = "<< cnt << endl;
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }

}

int main()
{
    for(uint64_t i = 0;i<N;i++)
    {
        pthread_t tid;
        pthread_create(&tid,nullptr,Func,(void*)i);
        usleep(10);
    }

    while(true)
    {
        pthread_cond_signal(&cond);
        sleep(1);
    }

    return 0;
}